const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
//注册用户处理函数
exports.regUser = (req, res) => {
    const userinfo = req.body;
    if (!userinfo.username || !userinfo.password) return res.cc('用户名和密码不能为空！')
    userinfo.password = bcrypt.hashSync(userinfo.password, 10)
    let sql = 'select * from ev_users where username=?'
    db.query(sql, [userinfo.username], (err, data) => {
        if (err) return res.cc(err);
        if (data.length > 0) {
            return res.cc('用户名被占用，请更换其他用户名！')
        }
        let sql2 = 'insert into ev_users set ?';
        db.query(sql2, { username: userinfo.username, password: userinfo.password }, (err, data) => {
            if (err) return res.cc(err)
            if (data.affectedRows !== 1) {
                return res.cc('注册失败')
            }
            //注册成功
            res.send({
                status: 0,
                message: '注册成功！'
            })
        })
    })


}

//登录
exports.login = (req, res) => {
    let userinfo = req.body;
    if (!userinfo.username || !userinfo.password) return res.cc('用户名和密码不能为空！');
    let sql = 'select * from ev_users where username=?';
    db.query(sql, [userinfo.username], (err, data) => {
        if (err) return res.cc(err)
        if (data.length !== 1) return res.cc('用户名或密码错误');
        const comResult = bcrypt.compareSync(userinfo.password, data[0].password);
        if (!comResult) return res.cc('用户名或密码错误!');
        const user = { ...data[0], password: '', user_pic: '' }
        // console.log(user);
        const jwtSecretKey = 'itheima No1. ^_^';
        const tokenStr = jwt.sign(user, jwtSecretKey, { expiresIn: '9h' });
        res.send({
            status: 0,
            token: 'Bearer ' + tokenStr,
        })
    })

}